package code.oldCode.feishuSpecializedTraining.string;

/**
 * @author 26029
 * @date 2025/3/9
 * @description
 */
public class MyString {
    // 344. 反转字符串
    public void reverseString(char[] s) {
        int left = 0, right = s.length - 1;
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }

    // 541. 反转字符串 II
    public String reverseStr(String s, int k) {
        char[] sChar = s.toCharArray();
        int len = sChar.length;
        int left = 0;
        int right = k - 1;
        boolean re = true;
        while (right < len) {
            if (re) {
                reverseStrPos(sChar, left, right);
            }
            left = right + 1;
            right += k;
            re = !re;
        }
        if (re) {
            reverseStrPos(sChar, left, len - 1);
        }
        return new String(sChar);
    }
    public void reverseStrPos(char[] s, int left, int right) {
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }

    // LCR 122. 路径加密
    public String pathEncryption(String path) {
        StringBuilder sb = new StringBuilder();
        int len = path.length();
        for (int i = 0; i < len; i++) {
            Character c = path.charAt(i);
            if (c == '.')
                sb.append(' ');
            else
                sb.append(c);
        }
        return sb.toString();
    }

    // LCR 182. 动态口令
    public String dynamicPassword(String password, int target) {
        int len = password.length();
        if (len <= target)
            return password;
        String front = password.substring(0, target);
        String end = password.substring(target, len);
        return end + front;
    }
    public String dynamicPassword_(String password, int target) {
        // 只在本串操作，不申请额外空间（java不能在String操作，故转为char[]，暂不计入额外空间）
        char[] s = password.toCharArray();
        int len = s.length;
        if (len <= target)
            return password;
        // 左旋 target 次，用三次 reverse 实现
        reverseStrPos_(s, 0, len - 1);
        reverseStrPos_(s, 0, len - target - 1);
        reverseStrPos_(s, len - target, len - 1);
        return new String(s);
    }
    public void reverseStrPos_(char[] s, int left, int right) {
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}
